package com.oos.zone.wechat.mp.service.impl;

import com.google.common.collect.ImmutableMap;
import com.oos.zone.wechat.mp.service.WxMpEventNoticeService;
import lombok.extern.log4j.Log4j2;
import me.chanjar.weixin.mp.api.WxMpMessageRouter;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.config.WxMpConfigStorage;
import me.chanjar.weixin.mp.util.WxMpConfigStorageHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 功能描述：微信公众号消息事件处理
 *
 * @author 拓金辉
 * @version 1.0
 * @date 2021-08-08 11:58:43
 */
@Log4j2
@Service
public class WxMpEventNoticeServiceImpl implements WxMpEventNoticeService {

    @Resource
    private WxMpMessageRouter wxMpMessageRouter;

    @Resource
    private WxMpService wxMpService;

    @Override
    public String notice(String appId, String signature, String timestamp, String nonce, String msgSignature, String encryptedXml) {
        try {
            final WxMpService wxMpService = this.wxMpService.switchoverTo(appId);
            if (!wxMpService.checkSignature(timestamp, nonce, signature)) {
                throw new RuntimeException("验证消息来自微信服务器验证失败");
            }
            final WxMpConfigStorage wxMpConfigStorage = wxMpService.getWxMpConfigStorage();
            final WxMpXmlMessage wxMpXmlMessage = WxMpXmlMessage.fromEncryptedXml(encryptedXml, wxMpConfigStorage, timestamp, nonce, msgSignature);
            final ImmutableMap<String, Object> context = ImmutableMap.of("appId", appId);
            return wxMpMessageRouter.route(wxMpXmlMessage, context).toEncryptedXml(wxMpConfigStorage);
        } finally {
            WxMpConfigStorageHolder.remove();
        }

    }

    @Override
    public String verify(String appId, String signature, String timestamp, String nonce, String echoStr) {
        try {
            final WxMpService wxMpService = this.wxMpService.switchoverTo(appId);
            return wxMpService.checkSignature(timestamp, nonce, signature) ? echoStr : "验证URL失败";
        } finally {
            WxMpConfigStorageHolder.remove();
        }

    }

}
